package cn.itsource.user.service.impl;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.org.domain.TEmployee;
import cn.itsource.user.domain.Logininfo;
import cn.itsource.user.domain.User;
import cn.itsource.user.mapper.LogininfoMapper;
import cn.itsource.user.mapper.UserMapper;
import cn.itsource.user.service.IUserService;
import cn.itsource.basic.service.impl.BaseImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseImpl<User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private JavaMailSender sender;

    @Override
    public void delete(Long id) {
        super.delete(id);
        logininfoMapper.delete(id);
    }

    @Override
    public void patchDelete(List<Long> ids) {
        super.patchDelete(ids);
        logininfoMapper.patchDelete(ids);
    }

    @Override
    public AjaxResult disable(Long id) {
        //查询该id的用户
        /*User user = selectById(id);*/
        userMapper.disable(id);
        logininfoMapper.disable(id);
        return AjaxResult.me().setSuccess(true).setMessage("禁用成功");
    }

    @Override
    public AjaxResult enable(Long id) {
        //查询该id的用户
        /*User user = selectById(id);*/
        userMapper.enable(id);
        logininfoMapper.enable(id);
        return AjaxResult.me().setSuccess(true).setMessage("禁用成功");
    }

    @Override
    public AjaxResult phoneRegister(Map<String, String> map) {
        /**
         * 准备校验
         */
        //接收参数
        String phone = map.get("phone");
        String smsCode = map.get("smsCode");
        String password = map.get("password");
        String passwordRepeat = map.get("passwordRepeat");
        //空值校验
        if(StrUtil.isBlank(phone) || StrUtil.isBlank(smsCode) || StrUtil.isBlank(password) || StrUtil.isBlank(passwordRepeat)){
            return AjaxResult.me().setSuccess(false).setMessage("参数不能为空");
        }
        //密码验证
        if(!password.equals(passwordRepeat)){
            return AjaxResult.me().setSuccess(false).setMessage("两次密码不一致");
        }
        //redis中获取短信验证码
        Object obj = redisTemplate.opsForValue().get("register:" + phone);
        //短信验证码校验
        if (obj==null){
            return AjaxResult.me().setSuccess(false).setMessage("短信验证码已过期");
        }
        if (!smsCode.equals(obj.toString().split(":")[0])){
            return AjaxResult.me().setSuccess(false).setMessage("短信验证码错误");
        }

        /**
         * 存入数据库 user表和logininfo表
         */
        //构建User对象
        User user = MapToUser(phone,password);

        /*User user = new User();
        user.setPhone(phone);
        user.setPhone(phone);
        String salt = RandomUtil.randomString(32);
        String MD5Pwd = SecureUtil.md5(password + salt);
        user.setSalt(salt);
        user.setPassword(MD5Pwd);
        user.setState(1);*/

        //构建LoginInfo对象
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        //将LoginInfo对象存入数据库 ==>获取它的id给user对象
        logininfoMapper.insert(logininfo);
        user.setLogininfoId(logininfo.getId());
        //将User对象存入数据库
        userMapper.insert(user);

        return AjaxResult.me().setSuccess(true).setMessage("注册成功");
    }

    @Override
    public AjaxResult emailRegister(Map<String, String> map) {
        //接收参数
        String email = map.get("email");
        String password = map.get("password");
        String passwordRepeat = map.get("passwordRepeat");
        //校验是否为空
        if(StrUtil.isBlank(email) || StrUtil.isBlank(password)){
            return AjaxResult.me().setSuccess(false).setMessage("参数不能为空");
        }
        //校验两次密码是否一致
        if(!password.equals(passwordRepeat)){
            return AjaxResult.me().setSuccess(false).setMessage("两次密码不一致");
        }
        //构建User对象
        User user = new User();
        user.setUsername(email);
        user.setEmail(email);
        String salt = RandomUtil.randomString(32);
        String MD5Pwd = SecureUtil.md5(password + salt);
        user.setSalt(salt);
        user.setPassword(MD5Pwd);
        user.setState(0);

        //构建LoginInfo对象
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);

        //将LoginInfo对象存入数据库 ==>获取它的id给user对象
        logininfoMapper.insert(logininfo);
        user.setLogininfoId(logininfo.getId());

        //将User对象存入数据库
        userMapper.insert(user);

        try {
            //创建复杂邮件对象
            MimeMessage mimeMessage = sender.createMimeMessage();
            //发送复杂邮件的工具类
            //true - 能够添加附件
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom("2687194836@qq.com");
            helper.setSubject("店铺审核反馈");
            helper.setText("<h1>店铺审核已通过</h1><a href='http://localhost:8080/user/emailRegister/active/"+user.getId() + "'>点击激活账号</a>",true);
            //收件人
            helper.setTo(user.getEmail());
            sender.send(mimeMessage);
        }catch (Exception e){
            e.printStackTrace();
        }

        return AjaxResult.me().setSuccess(true).setMessage("注册成功");
    }

    @Override
    public void emailRegisterActive(Long id) {
        logininfoMapper.emailRegisterActive(id);
    }


    private User MapToUser(String phone,String password) {
            User user = new User();
            user.setUsername(phone);
            user.setPhone(phone);
            String salt = RandomUtil.randomString(32);
            String MD5Pwd = SecureUtil.md5(password + salt);
            user.setSalt(salt);
            user.setPassword(MD5Pwd);
            user.setState(1);
            return user;
    }
}
